package database;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

import objectView.DepartmentCom;
import utility.StringUtil;
import clientMain.Login;
import clientMain.Main;

public class ViewDepDelegate {
	
	/**
	 * @author Tidus
	 * @param comId
	 * @param page = 0 return [depId, depName]
	 * @param sort
	 * @param flag
	 * @return
	 */
	public Vector<DepartmentCom> getListDepInfo(int comId, int page, String sort, boolean flag){
		Vector<DepartmentCom> list = new Vector<DepartmentCom>();
		try {
			Login.conn.setAutoCommit(false);
			CallableStatement cst = Login.conn.prepareCall("{call sp_ListDepInfo(?,?,?,?,?)}");
			cst.setInt(1, comId);
			cst.setInt(2, Main.record);
			cst.setInt(3, page);
			cst.setString(4, sort);
			cst.setBoolean(5, flag);
			ResultSet rs = cst.executeQuery();
			while(rs.next()){
				DepartmentCom dep = new DepartmentCom();
				dep.setDepId(rs.getInt("Dep_Id"));
				dep.setDepName(StringUtil.getFilterIllegal(rs.getString("Dep_Name")));
				if(page !=0){
					dep.setDepDescribe(StringUtil.getFilterIllegal(rs.getString("Dep_Describe")));
					dep.setDepTotalEm(rs.getInt("Dep_TotalEm"));
					dep.setDepPhone(rs.getString("Dep_Phone"));
					dep.setDepAddress(StringUtil.getFilterIllegal(rs.getString("Dep_Address")),
							StringUtil.getFilterIllegal(rs.getString("DistrictName")), 
							StringUtil.getFilterIllegal(rs.getString("ProvinceName")));
				}
				list.add(dep);
			}
			Login.conn.commit();
		} catch (Exception e) {
			e.printStackTrace();
			list = null;
		}
		return list;
	}
	
	public DepartmentCom getDep(int depId){
		DepartmentCom depInfo = new DepartmentCom();
		try {
			Login.conn.setAutoCommit(false);
			CallableStatement cst = Login.conn.prepareCall(" {call sp_getDepartment(?)} ");
			cst.setInt(1, depId);
			ResultSet rs = cst.executeQuery();
			while(rs.next()){
				depInfo.setDepId(depId);
				depInfo.setDepName(StringUtil.getFilterIllegal(rs.getString("Dep_Name")));
				depInfo.setDepDescribe(StringUtil.getFilterIllegal(rs.getString("Dep_Describe")));
				depInfo.setDepTotalEm(rs.getInt("Dep_TotalEm"));
				depInfo.setDepPhone(StringUtil.getFilterIllegal(rs.getString("Dep_Phone")));
				depInfo.setDepAddress(StringUtil.getFilterIllegal(rs.getString("Dep_Address")),
						StringUtil.getFilterIllegal(rs.getString("DistrictName")),
						StringUtil.getFilterIllegal(rs.getString("ProvinceName")));
			}
		} catch (SQLException e) {
			e.printStackTrace();
			depInfo = null;
		}
		return depInfo;
	}
}
